package com.example.jxauflea.controller;

import com.example.jxauflea.annotation.SystemControllerLog;
import com.example.jxauflea.config.OSSProperties;
import com.example.jxauflea.pojo.*;
import com.example.jxauflea.service.GoodsService;
import com.example.jxauflea.util.JxauFleaUtil;
import com.example.jxauflea.util.ResultEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class GoodsController {


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OSSProperties ossProperties;

   @PostMapping("/goods/add/information")
   @ApiOperation(value = "用户发布商品", notes ="需要接收用户的id和基本的商品信息(包括商品图片)")
   public ResultEntity<String> doReleaseGoods(GoodsPO goodsPO,MultipartFile[] file){

       // 接收前端传过来的参数，并进行封装

       OrderPO orderPO=new OrderPO();
       goodsPO.setState(0);// 后续加上管理员，状态默认设置为0
       String goodsUUID = UUID.randomUUID().toString();
       goodsPO.setUuid(goodsUUID);

       // 封装订单数据
       orderPO.setUuid(UUID.randomUUID().toString());
       orderPO.setGoodsId(goodsUUID);
       orderPO.setUserIdSell(goodsPO.getUserId());


       // 解析图片并上传
       List<GoodsImgPO> list=new ArrayList<>();
       if(file!=null&&file.length!=0){

           for (MultipartFile multipartFile : file) {
               try {
                   ResultEntity<String> stringResultEntity = JxauFleaUtil.uploadFileToOss(ossProperties.getEndPoint(),
                           ossProperties.getAccessKeyId(),
                           ossProperties.getAccessKeySecret(),
                           multipartFile.getInputStream(),
                           ossProperties.getBucketName(),
                           ossProperties.getBucketDomain(),
                           multipartFile.getOriginalFilename());
                   if("SUCCESS".equals(stringResultEntity.getResult())){
                       // 如果上传成功，则保存路径
                       GoodsImgPO goodsImgPO=new GoodsImgPO();
                       goodsImgPO.setGoodsId(goodsUUID);
                       String url=stringResultEntity.getData();
                       goodsImgPO.setImgUrl("Http://"+url);
                       list.add(goodsImgPO);
                   }else{
                       return ResultEntity.falseWithoutData("图片信息上传失败！");
                   }

               } catch (IOException e) {
                   e.printStackTrace();
                   return ResultEntity.falseWithoutData(e.getMessage());
               }
           }

       }

       try{
           goodsService.releaseGoods(goodsPO,list,orderPO);
           return ResultEntity.successWithoutData();

       }catch (Exception e){
           return ResultEntity.falseWithoutData(e.getMessage());
       }

   }

    @SystemControllerLog(actionType = "用户操作",descrption = "用户发布商品评论")
    @PostMapping("/goods/add/comment")
    @ApiOperation(value = "用户发布商品评论", notes ="需要接收用户的id、评论内容、商品的id")
    public ResultEntity<String> doGoodsComment(@RequestBody Map<String,String> map){

        CommentPO commentPO=new CommentPO();
        commentPO.setContent(map.get("content"));
        commentPO.setGoodsId(map.get("goodsId"));
        commentPO.setUserId(map.get("userId"));
        commentPO.setUuid(UUID.randomUUID().toString());

        try{

            goodsService.saveGoodsComment(commentPO);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }
    }

    @SystemControllerLog(actionType = "用户操作",descrption = "用户收藏商品")
    @PostMapping("/goods/add/collection")
    @ApiOperation(value = "用户收藏商品", notes ="需要接收用户的id、商品的id")
    public ResultEntity<String> doAddCollection(@RequestBody Map<String,String> map){
        CollectionPO collectionPO=new CollectionPO();
        collectionPO.setGoodsId(map.get("goodsId"));
        collectionPO.setUserId(map.get("userId"));

        try{
            goodsService.saveCollection(collectionPO);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }
    }


  /*
    // 分页查询版本
    @GetMapping("/goods/get/collection")
    @ApiOperation(value = "用户查看收藏夹", notes ="需要接收用户的id")
    public ResultEntity<PageInfo<CollectionPO>> doGetCollection(@RequestParam(value = "pageNum",required = false,defaultValue ="1")Integer pageNum,
                                                                @RequestParam(value = "pageSize",required = false,defaultValue ="5")Integer pageSize,
                                                                @RequestParam(value = "userId")String userId){

        // 需要进行分页操作
        try{
            PageHelper.startPage(pageNum,pageSize);// 下一句一定得是service调用方法，不然报错
            List<CollectionPO> Collections=goodsService.getUserCollection(userId);
            PageInfo<CollectionPO> pageInfo = new PageInfo<>(Collections);
            return ResultEntity.successWithData(pageInfo);

        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }

    }*/
    @SystemControllerLog(actionType = "用户操作",descrption = "用户查看收藏夹")
    @GetMapping("/goods/get/collection")
    @ApiOperation(value = "用户查看收藏夹", notes ="需要接收用户的id")
    public ResultEntity<List<GoodsVO>> doGetCollection(@RequestParam(value = "userId")String userId){

        // 需要进行分页操作
        try{
            List<GoodsVO> Collections=goodsService.getUserCollection(userId);
            return ResultEntity.successWithData(Collections);

        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }

    }



    @SystemControllerLog(actionType = "用户操作",descrption = "用户移除收藏夹商品")
    @PostMapping("/goods/delete/collection")
    @ApiOperation(value = "用户移除收藏夹中商品", notes ="需要接收用户的id,移除商品的id")
    public ResultEntity<String> doDeleteCollection(@RequestBody Map<String,String> map){

        CollectionPO collectionPO=new CollectionPO();
        collectionPO.setGoodsId(map.get("goodsId"));
        collectionPO.setUserId(map.get("userId"));
        try{
            goodsService.deleteCollection(collectionPO);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }
    }

    @SystemControllerLog(actionType = "用户操作",descrption = "用户查看商品详情")
    @PostMapping("/goods/get/detail")
    @ApiOperation(value = "查看商品详情", notes ="注意历史浏览功能，对于开启该功能的用户需要传入id，需要参数商品的id和用户的id（可省）")
    public ResultEntity<GoodsVO> doGetGoodDetail(@RequestBody Map<String,String> map){

        String goodsId = map.get("goodsId");
        String userId = map.get("userId");
        try{
           GoodsVO goodsVO= goodsService.getGoodsDetail(goodsId,userId);
           return ResultEntity.successWithData(goodsVO);
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }


    }


    @PostMapping("/goods/update/information")
    @ApiOperation(value = "更改用户发布的商品文字信息",notes ="需要参数商品的id、修改后商品的信息")
    public ResultEntity<String> doupdateInformation(@RequestBody Map<String,String> map){

        // 接收前端传过来的参数，并进行封装
        GoodsPO goodsPO=new GoodsPO();
        goodsPO.setGoodsName(map.get("goodsName"));
        goodsPO.setPrice(Double.parseDouble(map.get("price")));
        goodsPO.setDescription(map.get("description"));
        goodsPO.setType(map.get("type"));
        goodsPO.setQuantity(Integer.valueOf(map.get("quantity")));
        String goodsUUID = UUID.randomUUID().toString();
        goodsPO.setUuid(goodsUUID);


        try{
            goodsService.updateGoods(goodsPO);
            return ResultEntity.successWithoutData();

        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }

    }

    @PostMapping("/goods/update/img/information")
    @ApiOperation(value = "更改用户发布的商品图片信息",notes ="需要参数商品的id、图片")
    public ResultEntity<String> doupdateImgInformation(@RequestBody Map<String,String> map,MultipartFile[] file) {

        String goodsId = map.get("goodsId");
        // 解析图片并上传
        List<GoodsImgPO> list=new ArrayList<>();
        if(file!=null&&file.length!=0){

            for (MultipartFile multipartFile : file) {
                try {
                    ResultEntity<String> stringResultEntity = JxauFleaUtil.uploadFileToOss(ossProperties.getEndPoint(),
                            ossProperties.getAccessKeyId(),
                            ossProperties.getAccessKeySecret(),
                            multipartFile.getInputStream(),
                            ossProperties.getBucketName(),
                            ossProperties.getBucketDomain(),
                            multipartFile.getOriginalFilename());
                    if("SUCCESS".equals(stringResultEntity.getResult())){
                        // 如果上传成功，则保存路径
                        GoodsImgPO goodsImgPO=new GoodsImgPO();
                        goodsImgPO.setGoodsId(goodsId);
                        goodsImgPO.setImgUrl(stringResultEntity.getMessage());
                        list.add(goodsImgPO);
                    }else{
                        return ResultEntity.falseWithoutData("图片信息上传失败！");
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultEntity.falseWithoutData(e.getMessage());
                }
            }

            try{
                goodsService.updateGoodsImg(list,goodsId);
                return ResultEntity.successWithoutData();
            }catch (Exception e){
                return ResultEntity.falseWithoutData(e.getMessage());
            }

        }else{
            return ResultEntity.falseWithoutData("图片为空！");
        }
    }

    @SystemControllerLog(actionType = "用户操作",descrption = "用户查看发布的商品")
    @PostMapping("/goods/get/user/publish")
    @ApiOperation(value = "查询用户发布的商品",notes ="需要用户的id")
    public ResultEntity<List<GoodsVO>> doGetUserGoods(@RequestBody Map<String,String> map){

        try{
            List<GoodsVO> list= goodsService.getUserPublish(map.get("userId"));
            return ResultEntity.successWithData(list);
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }
    }

    @SystemControllerLog(actionType = "用户操作",descrption = "用户查看购物车")
    @GetMapping("/get/user/shopcar/goods")
    @ApiOperation(value = "查询用户购物车",notes ="需要用户的id")
    public ResultEntity<List<ShopCarVO>> doGetUserShopCar(@RequestParam("userId")String userId){


        try{
            List<ShopCarVO> list=goodsService.getUserShopCar(userId);
            return ResultEntity.successWithData(list);
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }


    }

    @PostMapping("/save/user/shopcar/goods")
    @ApiOperation(value = "用户添加商品至购物车",notes ="需要用户的id、商品的id")
    public ResultEntity<String> doSaveUserShopCar(@RequestBody Map<String,String> map){

        try{
            ShopCarPO shopCarPO=new ShopCarPO();
            shopCarPO.setUuid(UUID.randomUUID().toString());
            shopCarPO.setGoodsId(map.get("goodsId"));
            shopCarPO.setUserId(map.get("userId"));
            goodsService.saveUserShopCar(shopCarPO);
            return ResultEntity.successWithoutData();
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }

    }

    @SystemControllerLog(actionType = "用户查看",descrption = "用户查看浏览历史")
    @GetMapping("/get/user/view/history/goods")
    @ApiOperation(value = "用户查看浏览历史",notes ="需要用户的id")
    public ResultEntity<List<HistoryVO>> doGetUserViewHistory(@RequestParam String userId){

        try{
            List<HistoryVO> list=goodsService.getUserHistoryVO(userId);
            return ResultEntity.successWithData(list);
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }

    }

    @SystemControllerLog(actionType = "用户删除",descrption = "用户删除浏览历史")
    @PostMapping("/delete/user/view/history/goods")
    @ApiOperation(value = "用户删除浏览历史",notes ="需要用户的id,商品的id")
    public ResultEntity<List<GoodsVO>> doDeleteUserViewHistory(@RequestBody Map<String,String> map){

        try{
            HistoryPO history=new HistoryPO();
            String userId = map.get("userId");
            String goodsId = map.get("goodsId");
            history.setUserId(userId);
            history.setGoodsId(goodsId);
            goodsService.deleteHistory(history);
            List<GoodsVO> list=goodsService.getUserViewHistory(userId);
            return ResultEntity.successWithData(list);
        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }

    }

    @SystemControllerLog(actionType = "用户操作",descrption = "用户下架商品")
    @PostMapping("/sold/out/user/good")
    @ApiOperation(value = "用户下架商品",notes ="需要用户的id,商品的id")
    public ResultEntity<String> doSoldOutUserGood(@RequestBody Map<String,String> map){

        try{
            GoodsPO goodsPO=new GoodsPO();
            goodsPO.setUserId(map.get("userId"));
            goodsPO.setUuid(map.get("goodsId"));
            goodsService.soldOutGood(goodsPO);
            return ResultEntity.successWithoutData();

        }catch (Exception e){
            return ResultEntity.falseWithoutData(e.getMessage());
        }


    }




}
